package com.zhenwei.zscm.service;

import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.RestResult;
import com.zhenwei.zscm.common.exception.CustomException;
import com.zhenwei.zscm.model.dto.dict.DictDTO;
import com.zhenwei.zscm.model.enums.RepairStateEnum;
import com.zhenwei.zscm.model.enums.RoleEnum;
import com.zhenwei.zscm.model.vo.dict.DictVO;
import com.zhenwei.zscm.model.vo.dict.QueryDictVO;
import com.zhenwei.zscm.repo.DictRepo;
import com.zhenwei.zscm.repo.LogRepo;
import com.zhenwei.zscm.repo.RoleAuthRepo;
import com.zhenwei.zscm.repo.UserRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
public class DictService {
    private final LogRepo logRepo;
    private DictRepo dictRepo;
    private RoleAuthRepo roleAuthRepo;
    private UserRepo userRepo;
    private final String LOG_TYPE = "字典管理";
    public RestResult getList(String dictType){
        List<DictDTO> list = dictRepo.getList(dictType);
        return RestResult.success(list, list.size());
    }

    public RestResult addDict(DictVO vo){
        if("REPAIR_STATE".equals(vo.getDictType()) && (RepairStateEnum.CHECKING.name().equals(vo.getCode()) || RepairStateEnum.REPAIRED.name().equals(vo.getCode()))){
            return RestResult.fail(RestMsg.REPAIR_STATE_CANT_MAINTAIN);
        }
        if("ROLE".equals(vo.getDictType()) && (RoleEnum.ADMIN.name().equals(vo.getCode()) || RoleEnum.USER.name().equals(vo.getCode()))) {
            return RestResult.fail(RestMsg.CAN_NOT_CREATE_ADMIN);
        }
        boolean success = dictRepo.addDict(vo);
        if(!success){
            return RestResult.fail(RestMsg.FAILURE);
        }
        if("ROLE".equals(vo.getDictType())) {
            // 给角色添加一行权限数据
            boolean created = roleAuthRepo.createEmptyAuth(vo.getCode(), vo.getName());
            if (!created) {
                throw new CustomException(RestMsg.FAILURE);
            }
        }
        logRepo.createAsync(LOG_TYPE, "新建字典->" + vo);
        return RestResult.success();
    }
    public RestResult updateDict(DictVO vo){
        if("REPAIR_STATE".equals(vo.getDictType()) && (RepairStateEnum.CHECKING.name().equals(vo.getCode()) || RepairStateEnum.REPAIRED.name().equals(vo.getCode()))){
            return RestResult.fail(RestMsg.REPAIR_STATE_CANT_MAINTAIN);
        }
        if("ROLE".equals(vo.getDictType()) && (RoleEnum.ADMIN.name().equals(vo.getCode()) || RoleEnum.USER.name().equals(vo.getCode()))) {
            return RestResult.fail(RestMsg.CAN_NOT_CREATE_ADMIN);
        }
        var dict = dictRepo.getDict(vo.getCode(), vo.getDictType());
        if (dict != null && !dict.getGuid().equals(vo.getGuid())) {
            return RestResult.fail(RestMsg.DICT_CODE_EXISTS);
        }
        boolean updated = dictRepo.update(vo);
        if(!updated){
            return RestResult.fail(RestMsg.FAILURE);
        }
        logRepo.createAsync(LOG_TYPE, "修改字典->" + vo);
        return RestResult.success();
    }
    @Transactional(rollbackFor = { CustomException.class , Exception.class })
    public RestResult delete(DictVO vo) {
        if("REPAIR_STATE".equals(vo.getDictType())){
            return RestResult.fail(RestMsg.REPAIR_STATE_CANT_MAINTAIN);
        }
        if("ROLE".equals(vo.getDictType()) && (RoleEnum.ADMIN.name().equals(vo.getCode()) || RoleEnum.USER.name().equals(vo.getCode()))) {
            return RestResult.fail(RestMsg.CAN_NOT_DELETE_ADMIN);
        }
        boolean deleted = dictRepo.delete(vo);
        if(!deleted){
            return RestResult.fail(RestMsg.FAILURE);
        }
        // 如果删除了角色，则删除对应的权限
        if("ROLE".equals(vo.getDictType())){
            roleAuthRepo.deleteRoleAuth(vo.getCode());//                throw new CustomException(RestMsg.FAILURE);
        }
        // 将用户设置为普通用户角色
        if(!userRepo.checkExistsRoleUser(vo.getCode())){
            return RestResult.success();
        }
        boolean updated = userRepo.updateUserRoleToNormalUser(vo.getCode());
        if(!updated){
            throw new CustomException(RestMsg.FAILURE);
        }
        logRepo.createAsync(LOG_TYPE, "删除字典->" + vo);
        return RestResult.success();
    }

    public RestResult getDictType(){
        List<String> dictType = dictRepo.getDictType();
        return RestResult.success(dictType, 0);
    }

    public RestResult page(QueryDictVO query) {
        List<DictDTO> list = dictRepo.page(query);
        return RestResult.success(list, query.getTotalCount());
    }
}
